package com.example.demo.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlSendPost {

    private static final Logger log = LoggerFactory.getLogger(XmlSendPost.class);

    public static void main(String[] args) {
        try {
            String xml = "";
            String secret = "8SbKwWjzrY43X/QS3KF2HQ==";
            String public_key = "jxYoysLtr=jUGfCeTlrhqMA=";    //主站约定
//        String public_key = " wxUgtsLot=iPGfCfTlwnqWT=";  //地方约定
            String author_id = "104453";

            Long timestamp = System.currentTimeMillis();
            Map<String, String[]> params = new HashMap<String, String[]>();
            params.put("public_key", new String[]{public_key});
            params.put("author_id", new String[]{author_id});
            params.put("timestamp", new String[]{timestamp.toString()});
            String token = generateToken(secret, params);

            // 创建XML文档
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            // 创建根节点
            Element mmsContent = doc.createElement("mmscontent");
            doc.appendChild(mmsContent);

            // 添加子节点
            addElement(doc, mmsContent, "token", token);
            addElement(doc, mmsContent, "timestamp", timestamp.toString());
            addElement(doc, mmsContent, "contenttype", "news");
            addElement(doc, mmsContent, "operationtype", "add");

            // 创建target节点
            Element target = doc.createElement("target");
            mmsContent.appendChild(target);
            addCdataElement(doc, target, "cmsnode", "457645");
            addCdataElement(doc, target, "cmsfile", "0");

            // 创建content节点
            Element content = doc.createElement("content");
            mmsContent.appendChild(content);

            // contentinfo节点
            Element contentInfo = doc.createElement("contentinfo");
            content.appendChild(contentInfo);
            addCdataElement(doc, contentInfo, "indexid", "1740539559428148");
            addCdataElement(doc, contentInfo, "tableid", "0");
            addCdataElement(doc, contentInfo, "title", "意大利：泡泡魔术师  打造“我在泡泡中”");
            addCdataElement(doc, contentInfo, "cmspublishtime", "1741741986841");
            addElement(doc, contentInfo, "publishDate", "1292336308000");
            addCdataElement(doc, contentInfo, "isTVM", "0");
            addCdataElement(doc, contentInfo, "keyword", "罗马");
            addElement(doc, contentInfo, "templateid", "120669");
            addCdataElement(doc, contentInfo, "description", "");

            // extrainfo节点
            Element extraInfo = doc.createElement("extrainfo");
            content.appendChild(extraInfo);
            addCdataElement(doc, extraInfo, "shouldernote", "");
            addCdataElement(doc, extraInfo, "subtitle", "");
            addCdataElement(doc, extraInfo, "author", "");
            addCdataElement(doc, extraInfo, "authorid", "104453");
            addCdataElement(doc, extraInfo, "source", "央视网");
            addCdataElement(doc, extraInfo, "editor", "樊英武");

            // contentvideo节点
            Element contentVideo = doc.createElement("contentvideo");
            extraInfo.appendChild(contentVideo);
            addCdataElement(doc, contentVideo, "video", "http://recordcdn-sz.qukanvideo.com/upload/vod/user1720665496623010/1740539559428148/origin.mp4")
                    .setAttribute("name", "NAME");
            addElement(doc, contentVideo, "videolength", "40050");
            addCdataElement(doc, extraInfo, "programtext", "programtextprogramtextprogramtext");

            // programpicture节点
            Element programPicture = doc.createElement("programpicture");
            extraInfo.appendChild(programPicture);
            addCdataElement(doc, programPicture, "pic", "http://recordcdn-sz.qukanvideo.com/userUpload/1720665496623010/1740539559428148/picture/prescreen.png")
                    .setAttribute("name", "NAME");

            addCdataElement(doc, extraInfo, "cmspublishtime", "1741741986841");

            // 将XML转换为字符串
            String xmlString = documentToString(doc);
             log.info("xmlString:{}",xmlString);
            // 发送POST请求
//            String response = sendPostRequest("http://10.3.39.93:8930/tv2cms", xmlString);
//            System.out.println("Response:\n" + response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addElement(Document doc, Element parent, String tagName, String textContent) {
        Element element = doc.createElement(tagName);
        element.setTextContent(textContent);
        parent.appendChild(element);
    }

    private static Element addCdataElement(Document doc, Element parent, String tagName, String data) {
        Element element = doc.createElement(tagName);
        CDATASection cdata = doc.createCDATASection(data);
        element.appendChild(cdata);
        parent.appendChild(element);
        return element;
    }

    private static String documentToString(Document doc) throws Exception {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "GBK");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        DOMSource source = new DOMSource(doc);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        transformer.transform(source, new StreamResult(bos));
        return bos.toString("GBK");
    }

    private static String sendPostRequest(String url, String xmlData) throws IOException {
        HttpURLConnection conn = null;
        try {
            URL requestUrl = new URL(url);
            conn = (HttpURLConnection) requestUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/xml; charset=GBK");
            conn.setDoOutput(true);

            try (OutputStream os = conn.getOutputStream()) {
                byte[] input = xmlData.getBytes("GBK");
                os.write(input, 0, input.length);
            }

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "GBK"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    return response.toString();
                }
            } else {
                throw new IOException("HTTP error code: " + responseCode);
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**  2019-04-05 caiweihui add
     * 生成接口签名
     *
     * @param secret 分配密钥
     * @param params URL参数列表
     * @return
     */

    public static   String generateToken(String secret, Map<String, String[]> params) {
        StringBuilder builder = new StringBuilder();
        builder.append(secret).append("&");

        Map<String, String[]> cloneMap = new HashMap<String, String[]>(params);
        cloneMap.remove("token");

        String[] keys = sortKeys(cloneMap.keySet().toArray(new String[0]));
        StringBuilder kv = new StringBuilder();

        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            String[] values = params.get(key);
            if (values != null && values.length > 0) {
                kv.append(key).append("=").append(values[0]);
            }

            if (i < (keys.length - 1)) {
                kv.append("&");
            }
        }

        if (kv.length() > 0) {
            builder.append("&").append(encode(kv.toString()));
        }

        return DigestUtils.md5Hex(builder.toString());
    }


    /**
     * key排序
     * @param keys key数组
     * @return 排序后的key数组
     */

    public static String[] sortKeys(String[] keys) {
        for (int i = 0; i < keys.length - 1; i++) {
            for (int j = i + 1; j < keys.length; j++) {
                String temp = "";

                if (keys[i].compareTo(keys[j]) > 0) {
                    temp = keys[j];
                    keys[j] = keys[i];
                    keys[i] = temp;
                }
            }
        }
        return keys;
    }

    /**
     * UTF-8编码
     * @param value 待编码数据
     * @return 编码后数据
     */

    public static    String encode(String value) {
        String result = null;

        try {
            result = URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            result = "";
        }

        return result;
    }
}
